package com.aizuda.boot.modules.business.contract_import.service.impl;

import cn.hutool.http.Header;
import com.aizuda.boot.modules.business.contract_import.service.ContractImportService;
import com.aizuda.boot.modules.file.util.FileResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 合同导入服务实现类
 */
@Slf4j
@Service
public class ContractImportServiceImpl implements ContractImportService {

    @Override
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            // 从静态资源中读取模版文件
            ClassPathResource resource = new ClassPathResource("static/documents/合同表单导入模版.xlsx");
            
            if (!resource.exists()) {
                log.error("合同表单导入模版文件不存在");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "模版文件不存在");
                return;
            }
            
            // 读取文件内容
            InputStream inputStream = resource.getInputStream();
            byte[] fileContent = FileCopyUtils.copyToByteArray(inputStream);
            
            // 设置文件名
            String fileName = "合同表单导入模版.xlsx";
            
            // 使用项目标准的文件响应工具类设置下载头
            FileResponseUtil.setDownloadFileHeader(response, fileName, (long) fileContent.length);
            
            // 写入响应流
            response.getOutputStream().write(fileContent);
            response.getOutputStream().flush();
                    
        } catch (IOException e) {
            log.error("下载合同表单导入模版失败", e);
            throw e;
        }
    }
}